package com.workflow.workflowproject.listener;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * 流程结束监听
 */
@Slf4j
@Component
public class EndFlowListener implements FlowableEventListener {

    private static EndFlowListener endAssigneeListener;
    @Autowired
    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    @PostConstruct
    public void init(){
        endAssigneeListener = this;
        endAssigneeListener.processEngine =this.processEngine;
    }

    @Override
    public void onEvent(FlowableEvent event) {
        log.info(" -------------------------------------------流程结束时监听-------------------------start");
        FlowableEntityEvent engineEvent = (FlowableEntityEvent)event;
        Object entity = engineEvent.getEntity();
        ExecutionEntityImpl executionEntity = (ExecutionEntityImpl) entity;
        ProcessInstance processInstance = processEngine.getRuntimeService().createProcessInstanceQuery()
                .processInstanceId(executionEntity.getProcessInstanceId())
                .singleResult();
        log.info("进入结束监听");
        log.info("进入类型:" + event.getType());
        log.info("流程实例ID:" + executionEntity.getProcessInstanceId());
        log.info("流程业务ID：" + processInstance.getBusinessKey());

    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return "";
    }
}
